package electionCtrl;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.UUID;
import javax.xml.stream.XMLStreamException;

import xml.MockVotingXMLReader;
import xml.MockVotingXMLWriter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.*;

public class Election
{
	/**
	 * This instance field is used to catch the Candidate array object in the constructor.
	 **/
	private Candidate[] candidates;
	/**
	 * This instance field is used to tell the program if the elections is still happening.
	 **/
	private boolean electionIsHappening = false;
	/**
	 * This instance field is used to create and arrayList of admins.
	 **/
	private List<Admin> admins = new ArrayList<Admin>();
//	/**
//	 * This instance field is used to create and arrayList of Strings.
//	 **/
//	private ArrayList<String> passwords = new ArrayList<String>();
	/**
	 * This instance field is used to create and arrayList of Votes.
	 **/
	private ArrayList<Vote> currentVotes = new ArrayList<Vote>();

	public Election(final Candidate[] candidateList)
	{
		this.candidates = candidateList;
		this.currentVotes = new ArrayList<Vote>();
	}
	
	/**
	 * The constructor for the Election class.
	 * @param candidateList the list of candidates for the Election
	 * @param Admin firstAd the first Admin- all elections require an Admin!
	 **/
	public Election(final Candidate[] candidateList, final Admin firstAd)
	{
		this(candidateList);
		this.admins.add(firstAd);
	}

	//constructing an election out of a MockVotingXMLReader
	//Expects setup formatting
	public Election(MockVotingXMLReader reader) throws XMLStreamException {
		currentVotes = new ArrayList<Vote>();
		int candidCount = 0;
		while (reader.hasNext()) {
			String next = reader.next();
			if (next.equals("<CandidateCount>")) { candidates = new Candidate[Integer.parseInt(reader.next())];}//next value will be the value after the <size> tag.
			if (next.equals("<Admin>")) { admins.add(new Admin(reader));}
			if (next.equals("<Candidate>") && candidates != null) {//check to ensure that the array isn't empty
				candidates[candidCount] = new Candidate(reader);
				candidCount++;
			}
		}
	}

	public void writeVotesToXML(MockVotingXMLWriter writer) throws XMLStreamException, IOException {//code for writing election from Vote
		writer.openDocument();
		writer.writeStartElement("Votes");
		writer.writeComment("A new set of votes!");
		writer.writeNewline();
		writer.pushHierarchy();
		for (Vote v : currentVotes)
		{
			if(v == null)
			{
				continue;
			}
			v.writeToXML(writer);
		}
		writer.pullHierarchy();
		writer.writeEndElement();
		writer.closeDocument();
	}
	
	public void writeCandidatesToXML(MockVotingXMLWriter writer) throws XMLStreamException, IOException {//code for writing election from setup
		writer.openDocument();
		writer.writeComment("A new election!");
		writer.writeNewline();
		writer.writeStartElement("Election");
		writer.writeNewline();
		writer.pushHierarchy();
		writer.writeTag("CandidateCount",Integer.toString(candidates.length));
		for(int i = 0; i < admins.size(); i++) {
			admins.get(i).writeToXML(writer);
		}
		
		for (int i = 0; i < candidates.length; i++) {
			candidates[i].writeToXML(writer);
		}
		
		writer.pullHierarchy();
		writer.writeEndElement();
		writer.closeDocument();
		
		System.exit(0);
	}
	
	/**
	 * 
	 * @return Returns null if there is an error.
	 */
	public String getFileName(){
		InetAddress i = null;
		try
		{
			i = InetAddress.getLocalHost();
		}
		catch(UnknownHostException e)
		{
			e.printStackTrace();
			return "";
		}
		String name = i.getHostName();
		String addr = i.getHostAddress();
		String uuid = UUID.randomUUID().toString();
		addr = addr.replaceAll("\\.","-");//replace all periods with dashes to avoid confusion in file extension
		String hString = name + "-" + addr + "-" + uuid;
		
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.reset();
			m.update(hString.getBytes());
			byte[] digest = m.digest();
		
			StringBuffer hexString = new StringBuffer();
			for (int j = 0; j < digest.length; j++) {
				hexString.append(Integer.toHexString(0xFF & digest[j]));
			}
			
			return hexString.toString().substring(0,8);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
   }

	//	/**
	//	 * A method for determining that a password is valid or not.
	//	 * Precondition: pass is a String of length 16
	//	 * Postcondition: pass is removed from the passwords array
	//	 * @param pass the passcodeto be tested
	//	 * @return whether or not the password is valid
	//	 **/
	//	protected boolean isValidPass(String pass) throws Exception{
	//		if(pass.length() != 16) throw new IllegalArgumentException("Password must be a 16-character alphanumeric string");
	//		for(String i : passwords) {
	//			if(i.equals(pass)) {
	//				passwords.remove(passwords.indexOf(i));
	//				return true;
	//			}
	//		}
	//		return false;
	//	}

	//	/**
	//	 * A method used for generating a 16 char length random password.
	//	 * (3616 possibilities)
	//	 * @return said random password
	//	 **/
	//	private static String generatePass(){
	//		String pass = "";
	//		String alphabet = "abcdefghijklmnopqrstuvwxyz";
	//		Random rand = new Random();
	//		for(int i = 0; i < 16; i++){
	//			int choice = rand.nextInt(37);
	//			if(choice < 11) pass += Integer.toString(choice);
	//			else pass += alphabet.charAt(choice-11);
	//		}
	//		return pass;
	//	}

	//	/**
	//	 * A method for generating a set of passwords and adding them to the passwords ArrayList.
	//	 * Postcondition: passwords has been populated with num new passwords
	//	 * @param num the number of passcodes to be generated
	//	 **/
	//	protected void generatePassList(int num){
	//		for(int i = 0; i < num; i++) {
	//			boolean alreadyExists = false;
	//			String newPass = generatePass();
	//			for(String s : passwords) {
	//				if(s.equals(newPass)) alreadyExists = true;
	//			}
	//			if(!alreadyExists) passwords.add(newPass);
	//			else i--;
	//		}
	//	}

	/**
	 * A method to add a Vote to currentVotes
	 * Postcondition: v has been placed in currentVotes.
	 * @param v the Vote to be added
	 **/
	protected void addVote(Vote v){
		currentVotes.add(v);
	}

	/**
	 * A method to determine the present state of the election (happening or not).
	 * @return the present state of the election
	 **/
	public boolean isElection(){
		return electionIsHappening;
	}

	/**
	 * A method to toggle whether or not the election is happening.
	 * Postcondition: electionIsHappening is equal to val
	 * @param val the new boolean value- T for happening, F for not happening
	 **/
	public void setElection(boolean val) {
		electionIsHappening = val;
	}

	/**
	 * A method to determine if an Admin is legal to do work on the Election.
	 * @param password the Admin to be tested
	 * @return whether or not the Admin is legal
	 **/
	public boolean isLegalAdmin(String username, String password)
	{
		for(Admin ad : this.admins)
		{
			if (ad.checkUsername(username) && ad.checkPassword(password))
				return true;
		}
		return false;
	}
	
	public boolean isLegalAdmin(Admin a)
	{
		for(Admin ad : this.admins)
		{
			if(ad.equals(a))
				return true;
		}
		return false;
	}

	/**
	 * A method to add an Admin to the admins ArrayList.
	 * Postcondition: admins has had Admin a added to it
	 * @param a the Admin to be added
	 **/
	public void addAdmin(Admin a) {
		admins.add(a);
	}
	
	public Admin[] getCurrAdmins()
	{
		return this.admins.toArray(new Admin[0]);
	}

	/** 
	 * A method to return the array of Candidates relevant to the election.
	 * @return the candidates
	 **/
	public Candidate[] getCandidates() 
	{
		int size = this.candidates.length;
		Candidate[] cand = new Candidate[size];
		for(int i = 0; i < size; i++)
		{
			cand[i] = this.candidates[i];
		}
		return cand;
	}

	//	/**
	//	 * A method to return the passwords that are legal for this election.
	//	 * Expected to be used to print out passwords for an Admin.
	//	 * @return the ArrayList<String> of passwords.
	//	 **/
	//	private ArrayList<String> getPasswords() 
	//	{
	//		return passwords;   
	//	}

	/**
	 * A method for handling the tabulation of votes by candidate
	 * Precondition: currentVotes is of size > 0
	 * @return a Hashtable containing corresponding key,value pairs with candidates and their corresponding vote counts (values obtained from hashTable by passing in Candidate w/ get method (i.e. h.get(Parker) will return number of votes for Parker.))
	 **/
	protected Hashtable<Candidate, Integer> tabulateVotes() throws Exception{
		if(currentVotes.size() == 0) throw new IllegalStateException("No votes have been recorded");
		Hashtable<Candidate,Integer> h = new Hashtable<Candidate,Integer>();
		ArrayList<Candidate> candids = new ArrayList<Candidate>();
		ArrayList<Integer> counts = new ArrayList<Integer>(); 
		for (Vote v : currentVotes) {
			Candidate c = v.candidate;
			int test = -1;
			for (int j = 0; j < candids.size();j++) {
				Candidate c2 = candids.get(j);
				if (c2.name.equals(c.name) && c2.seat.equals(c.seat) && c2.party.equals(c.party)) test = j;
				if (test >= 0) {
					counts.set(test,counts.get(test)+ 1);        
				} else {
					candids.add(c);
					counts.add(1);
				}
			}
			for (int i = 0; i < candids.size();i++) {//candids.size() should == counts.size()
				if(candids.get(i) != null && counts.get(i) != null){//To make sure that the put() precondition is satisfied
					h.put(candids.get(i),counts.get(i));
				}
			}
		}
		return h;
	}
	//	/**
	//	 * This returnes the generated passwords for the voters so they can vote.
	//	 * @return ArraList<String> this is what is returned.
	//	 **/
	//	protected ArrayList<String> getVotePass()
	//	{
	//		return passwords;
	//	}
	
	public boolean equals(Object o)
	{
		if(!(o instanceof Election))
		{
			return false;
		}
		Election e = (Election)o;
		return e.candidates.equals(this.candidates);
	}
} 